<template>
    <Popup ref="popRef" :title="title" width="500px" async @confirm="submit" @close="$emit('close')">
        <div>
            <el-form label-width="90px" :model="formData" ref="formRef" :rules="rules" @submit.prevent>
                <el-form-item label="头像" prop="avatar" v-show="!(isOnlyShowStatus || isOnlyShowPassWord)">
                    <el-upload class="avatar-uploader" action="" :show-file-list="false"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus></Plus>
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="学号" prop="student_no" v-show="!(isOnlyShowStatus || isOnlyShowPassWord)">
                    <el-input placeholder="请输入学号" v-model="formData.student_no"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="real_name" v-show="!(isOnlyShowStatus || isOnlyShowPassWord)">
                    <el-input placeholder="请输入姓名" v-model="formData.real_name"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="phone" v-show="!(isOnlyShowStatus || isOnlyShowPassWord)">
                    <el-input placeholder="请输入联系方式" v-model="formData.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email" v-show="!(isOnlyShowStatus || isOnlyShowPassWord)">
                    <el-input placeholder="请输入邮箱" v-model="formData.email"></el-input>
                </el-form-item>
                <el-form-item label="院系/班级" prop="college" v-show="!(isOnlyShowStatus || isOnlyShowPassWord)">
                    <el-cascader style="width: 500px" v-model="formData.college" :options="data"></el-cascader>
                </el-form-item>
                <el-form-item label="登录密码" prop="password" v-show="isShowPassWordFormItem && !isOnlyShowStatus">
                    <el-input placeholder="请输入登录密码" type="password" v-model="formData.password"
                        show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="password_confirm" v-show="isShowPassWordFormItem && !isOnlyShowStatus">
                    <el-input placeholder="请输入确认密码" type="password" show-password
                        v-model="formData.password_confirm"></el-input>
                </el-form-item>

                <el-form-item label="选择状态" v-show="isShowStatus && isOnlyShowStatus">
                    <el-switch v-model="formData.status"></el-switch>
                </el-form-item>

                <el-form-item label="备注内容" prop="remark" v-show="isOnlyShowStatus">
                    <el-input size="medium" placeholder="请输入备注内容" v-model="formData.remark" :rows="4" type="textarea"
                        show-word-limit></el-input>
                </el-form-item>
            </el-form>
        </div>
    </Popup>
</template>

<script setup lang="ts">
import { addStudent, editStudent, getDepartmentList, uploadImage } from "@/api/consumer";
import feedback from "@/utils/feedback";
import { useRequest } from "vue-hooks-plus";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";

const props = withDefaults(
    defineProps<{
        //    是否显示密码
        isShowPassWordFormItem: boolean;
        // 是否显示状态
        isShowStatus: boolean;
        title: string;
        // 是否仅仅显示状态
        isOnlyShowStatus: boolean;
        // 是否仅仅显示密码
        isOnlyShowPassWord: boolean;
    }>(),
    {
        isShowPassWordFormItem: true,
        isShowStatus: true,
        title: "添加/编辑学生",
        isOnlyShowStatus: false,
        isOnlyShowPassWord: false,
    }
);

interface IFormData {
    avatar: string;
    student_no: string;
    phone: string;
    email: string;
    real_name: string;
    password: string;
    password_confirm: string;
    status: boolean;
    college: "";
    remark: string;
}

const emit = defineEmits(["close", "submit"]);

//弹框ref
const popRef = shallowRef();
//表单ref
const formRef = shallowRef<FormInstance>();

//表单数据
const formData: IFormData = reactive({
    avatar: "",
    student_no: "",
    real_name: "",
    email: "",
    phone: "",
    password: "",
    password_confirm: "",
    status: true,
    college: "",
    remark: "",
    id: ""
});

const rules = reactive<FormRules<IFormData>>({
    avatar: [
        {
            required: true,
            message: "请选择头像",
            trigger: "change",
        },
    ],
    student_no: [
        {
            required: true,
            message: "请填写学号",
            trigger: "change",
        },
    ],
    real_name: [
        {
            required: true,
            message: "请填写姓名",
            trigger: "change",
        },
    ],
    college: [
        {
            required: true,
            message: "请选择学院",
            trigger: "change",
        },
    ],
    email: [
        {
            required: true,
            message: "请填写邮箱号",
            trigger: "change",
        },
    ],
    phone: [
        {
            required: true,
            message: "请填写联系方式",
            trigger: "change",
        },
    ],
    password: [
        {
            required: true,
            message: "请填写密码",
            trigger: "change",
        },
    ],
    password_confirm: [
        {
            required: true,
            message: "请填写确认密码",
            trigger: "change",
        },
    ],
});

const beforeAvatarUpload: any = async (rawFile) => {


    const _res = await uploadImage({
        file: rawFile,
    });

    if (_res.url) {
        formData.avatar = _res.url;
    }
    return false;
};

const { runAsync } = useRequest(
    async () => {

        /* 如果是编辑 */
        if (formData.id) {
            return await editStudent({
                ...formData,
                status: formData.status ? 1 : 2,
                college_id: formData.college?.[0],
                classes_id: formData.college?.[1],
                id: formData?.id
            })
        } else {
            return await addStudent({
                ...formData,
                status: formData.status ? 1 : 2,
                college_id: formData.college?.[0],
                classes_id: formData.college?.[1],
                id: undefined
            });
        }

    },
    {
        manual: true,
    }
);

// 获取学院配置
const { data } = useRequest(async () => {
    const _Res = await getDepartmentList({
        page: 1,
        limit: 9999,
    });

    const list: any = [];

    _Res?.data?.forEach((_item) => {
        if (_item?.classes && _item?.classes?.length > 0) {
            list.push({
                value: _item.id,
                label: _item.name,
                children: _item?.classes?.map((_item2) => {
                    return {
                        value: _item2.id,
                        label: _item2.name,
                    };
                }),
            });
        }
    });

    console.log("_Res", list);
    return list;
});

//提交表单
const submit = async () => {
    try {
        await formRef.value?.validate();


        await runAsync();
        if (formData?.id) {
            feedback.msgSuccess("更新成功！");
        } else {
            feedback.msgSuccess("新增成功！");
        }

        popRef.value.close();
        emit("submit");
    } catch (error) { }
};

//打开弹框
const open = () => {
    popRef.value.open();
};

const setFormData = async (row: any) => {
    for (const key in formData) {
        if (row[key] != null && row[key] != undefined) {
            //@ts-ignore
            formData[key] = row[key];
        }
    }
};

defineExpose({ open, setFormData });
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #cccccc;
    width: 120px;
    height: 120px;
    text-align: center;
    font-family: 'Font Awesome 5 Pro Solid', 'Font Awesome 5 Pro Regular',
        'Font Awesome 5 Pro', sans-serif;
    font-weight: 900;
}
</style>
